import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import '../services/alger_api_service.dart';
import 'alger_mv_player_screen.dart';
import '../utils/util.dart';

class AlgerMvListScreen extends StatefulWidget {
  const AlgerMvListScreen({super.key});

  @override
  State<AlgerMvListScreen> createState() => _AlgerMvListScreenState();
}

class _AlgerMvListScreenState extends State<AlgerMvListScreen> {
  final AlgerApiService _api = AlgerApiService();
  final ScrollController _areaController = ScrollController();
  final List<String> _areas = const ['全部', '内地', '港台', '欧美', '日本', '韩国'];
  String _selectedArea = '全部';

  List<AlgerMv> _mvs = [];
  bool _loading = false;
  bool _loadingMore = false;
  int _limit = 42;
  int _offset = 0;
  bool _hasMore = true;

  @override
  void initState() {
    super.initState();
    _loadMvs(reset: true);
  }

  String _areaParam(String area) => area == '全部' ? '' : area;

  Future<void> _loadMvs({bool reset = false}) async {
    if (reset) {
      setState(() {
        _loading = true;
        _mvs = [];
        _offset = 0;
        _hasMore = true;
      });
    } else {
      setState(() => _loadingMore = true);
    }
    try {
      final list = await _api.fetchMvs(limit: _limit, offset: _offset, area: _areaParam(_selectedArea));
      setState(() {
        if (reset) {
          _mvs = list;
          _hasMore = list.length >= _limit;
        } else {
          _mvs.addAll(list);
          if (list.length < _limit) _hasMore = false;
        }
      });
    } catch (e) {
      debugPrint('加载 MV 列表失败: $e');
    } finally {
      if (mounted) {
        setState(() {
          _loading = false;
          _loadingMore = false;
        });
      }
    }
  }

  Future<void> _loadMore() async {
    if (_loadingMore || !_hasMore) return;
    setState(() => _loadingMore = true);
    try {
      final nextOffset = _offset + _limit;
      final list = await _api.fetchMvs(limit: _limit, offset: nextOffset, area: _areaParam(_selectedArea));
      setState(() {
        _offset = nextOffset;
        _mvs.addAll(list);
        if (list.length < _limit) _hasMore = false;
      });
    } catch (e) {
      debugPrint('加载更多 MV 失败: $e');
    } finally {
      if (mounted) setState(() => _loadingMore = false);
    }
  }

  @override
  Widget build(BuildContext context) {
    final isWide = CommonUtils.isWideScreen(context);
    final crossAxisCount = isWide ? 4 : 2;
    final spacing = 12.0;
    // 动态计算 childAspectRatio，尽量贴合卡片实际内容高度，消除底部空白
    final childAspectRatio = _computeChildAspectRatio(context, crossAxisCount, spacing);

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(height: 8),
        _buildAreaBar(),
        const SizedBox(height: 8),
        _loading
            ? const Center(child: CircularProgressIndicator())
            : Column(
                children: [
                  GridView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: crossAxisCount,
                      mainAxisSpacing: spacing,
                      crossAxisSpacing: spacing,
                      childAspectRatio: childAspectRatio,
                    ),
                    itemCount: _mvs.length,
                    itemBuilder: (context, index) {
                      final m = _mvs[index];
                      return GestureDetector(
                        onTap: () {
                          Navigator.of(context).push(
                            MaterialPageRoute(
                              builder: (_) => AlgerMvPlayerScreen(
                                mvId: m.id,
                                mvName: m.name,
                                coverUrl: m.coverUrl,
                              ),
                            ),
                          );
                        },
                        child: Container(
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(color: Colors.grey[300]!),
                            color: Colors.white,
                          ),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              ClipRRect(
                                borderRadius: const BorderRadius.only(
                                  topLeft: Radius.circular(12),
                                  topRight: Radius.circular(12),
                                ),
                                child: Stack(
                                  children: [
                                    AspectRatio(
                                      aspectRatio: 16 / 9,
                                      child: m.coverUrl.isNotEmpty
                                          ? CachedNetworkImage(imageUrl: m.coverUrl, fit: BoxFit.cover)
                                          : Container(color: Colors.grey[200]),
                                    ),
                                    Positioned(
                                      right: 8,
                                      bottom: 8,
                                      child: Container(
                                        padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                                        decoration: BoxDecoration(
                                          color: Colors.black.withOpacity(0.55),
                                          borderRadius: BorderRadius.circular(6),
                                        ),
                                        child: Text(
                                          _formatDuration(m.durationMs),
                                          style: const TextStyle(color: Colors.white, fontSize: 11),
                                        ),
                                      ),
                                    ),
                                    Positioned(
                                      left: 8,
                                      bottom: 8,
                                      child: Container(
                                        padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                                        decoration: BoxDecoration(
                                          color: Colors.black.withOpacity(0.55),
                                          borderRadius: BorderRadius.circular(6),
                                        ),
                                        child: Row(
                                          children: [
                                            const Icon(Icons.play_arrow, size: 12, color: Colors.white),
                                            const SizedBox(width: 2),
                                            Text(
                                              _formatPlayCount(m.playCount),
                                              style: const TextStyle(color: Colors.white, fontSize: 11),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.fromLTRB(8, 8, 8, 4),
                                child: Text(
                                  m.name,
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                  style: const TextStyle(
                                    fontSize: 13,
                                    fontWeight: FontWeight.w600,
                                    color: Colors.black87,
                                  ),
                                ),
                              ),
                              Padding(
                                padding: const EdgeInsets.fromLTRB(8, 0, 8, 6),
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: Text(
                                        m.artistName,
                                        maxLines: 1,
                                        overflow: TextOverflow.ellipsis,
                                        style: TextStyle(fontSize: 12, color: Colors.grey[700]),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
                  const SizedBox(height: 8),
                  Padding(
                    padding: const EdgeInsets.only(bottom: 12),
                    child: Center(
                      child: _loadingMore
                          ? const SizedBox(height: 32, width: 32, child: CircularProgressIndicator())
                          : _hasMore
                              ? FilledButton.icon(
                                  onPressed: _loadMore,
                                  icon: const Icon(Icons.expand_more),
                                  label: const Text('加载更多'),
                                )
                              : Text('没有更多了', style: TextStyle(color: Colors.grey[600])),
                    ),
                  ),
                ],
              ),
      ],
    );
  }

  Widget _buildAreaBar() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      height: 40,
      child: Scrollbar(
        controller: _areaController,
        thumbVisibility: true,
        interactive: true,
        child: ListView.separated(
          controller: _areaController,
          scrollDirection: Axis.horizontal,
          itemCount: _areas.length,
          separatorBuilder: (_, __) => const SizedBox(width: 8),
          itemBuilder: (context, index) {
            final a = _areas[index];
            final selected = a == _selectedArea;
            return GestureDetector(
              onTap: () {
                setState(() => _selectedArea = a);
                _loadMvs(reset: true);
              },
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                decoration: BoxDecoration(
                  color: selected ? Colors.blue.withOpacity(0.15) : Colors.white,
                  borderRadius: BorderRadius.circular(18),
                  border: Border.all(color: selected ? Colors.blue : Colors.grey[300]!),
                ),
                child: Text(
                  a,
                  style: TextStyle(
                    fontSize: 12,
                    color: selected ? Colors.blue[800] : Colors.black87,
                    fontWeight: selected ? FontWeight.w600 : FontWeight.w400,
                  ),
                ),
              ),
            );
          },
        ),
      ),
    );
  }

  String _formatDuration(int? ms) {
    if (ms == null || ms <= 0) return '--:--';
    final totalSec = (ms / 1000).round();
    final m = (totalSec ~/ 60).toString().padLeft(2, '0');
    final s = (totalSec % 60).toString().padLeft(2, '0');
    return '$m:$s';
  }

  String _formatPlayCount(int? count) {
    if (count == null || count <= 0) return '0';
    if (count >= 100000000) {
      final v = (count / 100000000);
      return '${v.toStringAsFixed(v >= 10 ? 0 : 1)}亿';
    }
    if (count >= 10000) {
      final v = (count / 10000);
      return '${v.toStringAsFixed(v >= 10 ? 0 : 1)}万';
    }
    return count.toString();
  }

  // 计算 Grid 子项的宽高比，使卡片高度更贴合内容，减少底部空白
  double _computeChildAspectRatio(BuildContext context, int crossAxisCount, double spacing) {
    final screenWidth = MediaQuery.of(context).size.width;
    const horizontalPadding = 32.0; // GridView 横向内边距：左右各 16
    final tileWidth = (screenWidth - horizontalPadding - spacing * (crossAxisCount - 1)) / crossAxisCount;

    // 封面高度（固定 16:9）
    final coverHeight = tileWidth * 9.0 / 16.0;

    // 文本与内边距的近似高度（两行标题 + 一行歌手 + 上下 padding）
    final titleFontSize = 10.0; // 与标题 Text 的 fontSize 保持一致
    final artistFontSize = 8.0; // 与歌手 Text 的 fontSize 保持一致
    final titleLineHeight = titleFontSize * 1.25; // 估算行高
    final artistLineHeight = artistFontSize * 1.25; // 估算行高
    const titleLines = 2;
    const verticalPadding = 8.0 + 4.0 + 6.0; // 上 8、标题下 4、歌手行下 6
    final textHeight = titleLineHeight * titleLines + artistLineHeight + verticalPadding;

    // 增加安全余量，避免极小的溢出提示（调试模式下容易出现 < 2px 的溢出）
    // const safeSlack = 2.0; // 额外留白
    final tileHeight = coverHeight + textHeight;
    final ratio = tileWidth / tileHeight;

    // 兜底处理，避免极端尺寸导致布局异常
    if (ratio.isNaN || ratio <= 0) return 1.0;
    // 对宽屏与窄屏分别做上限约束，避免过紧导致溢出
    final isWide = CommonUtils.isWideScreen(context);
    final maxRatio = isWide ? 0.99 : 0.99;
    return ratio.clamp(0.6, maxRatio);
  }
}
